package com.stylefeng.guns.modular.cash.controller;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.BaseModelWarpper;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.modular.borrowing.service.IBorrowingInfoService;
import com.stylefeng.guns.modular.borrowing.service.ICustomerinfoService;
import com.stylefeng.guns.modular.cash.service.ICashExpenditureService;
import com.stylefeng.guns.modular.cash.service.IDetailsService;
import com.stylefeng.guns.modular.system.model.CashExpenditure;
import com.stylefeng.guns.modular.system.model.Customerinfo;
import com.stylefeng.guns.modular.system.model.Details;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 现金收支报表控制器
 *
 * @author fengshuonan
 * @Date 2018-07-03 11:46:32
 */
@Controller
@RequestMapping("/cashExpenditure")
public class CashExpenditureController extends BaseController {

    private String PREFIX = "/cash/cashExpenditure/";

    @Autowired
    private ICashExpenditureService cashExpenditureService;

    @Autowired
    private IDetailsService detailsService;

    @Autowired
    private ICustomerinfoService customerinfoService;

    @Autowired
    private IBorrowingInfoService borrowingInfoService;
    /**
     * 跳转到现金收支报表首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "cashExpenditure.html";
    }

    /**
     * 跳转到添加现金收支报表
     */
    @RequestMapping("/cashExpenditure_add")
    public String cashExpenditureAdd(Model model) {
        List<Details>  list=detailsService.selectList(null);
        List<Customerinfo>  customerList=customerinfoService.selectList( new EntityWrapper<Customerinfo>()
                .eq("platform",ShiroKit.getUser().getDeptcode())
        );
        model.addAttribute("Details",list);
        model.addAttribute("Customerinfos",customerList);
        return PREFIX + "cashExpenditure_add.html";
    }


    /**
     * 跳转到添加现金收支 期初余额
     */
    @RequestMapping("/cashExpenditure_addBalance")
    public String cashExpenditureAddBalance() {
        return PREFIX + "cashExpenditure_addBalance.html";
    }

    /**
     * 跳转到导出页面
     */
    @RequestMapping("/cashExpenditure_export")
    public String bankExport() {
        return PREFIX + "cashExpenditure_export.html";
    }

    /**
     * 跳转到修改现金收支报表
     */
    @RequestMapping("/cashExpenditure_update/{cashExpenditureId}")
    public String cashExpenditureUpdate(@PathVariable Integer cashExpenditureId, Model model) {
        List<Details>  list=detailsService.selectList(null);
        List<Customerinfo>  customerList=customerinfoService.selectList( new EntityWrapper<Customerinfo>()
                .eq("platform",ShiroKit.getUser().getDeptcode())
        );
        model.addAttribute("Details",list);
        CashExpenditure cashExpenditure = cashExpenditureService.selectById(cashExpenditureId);
        model.addAttribute("Customerinfos",customerList);
        model.addAttribute("item",cashExpenditure);
        LogObjectHolder.me().set(cashExpenditure);
        return PREFIX + "cashExpenditure_edit.html";
    }

    /**
     * 获取现金收支报表列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(CashExpenditure cashExpenditure,@RequestParam(required = false) Integer type, @RequestParam(required = false) String beginDate,@RequestParam(required = false) String  endDate)throws Exception{

        //分页查询
        Page<CashExpenditure> page = new PageFactory<CashExpenditure>().defaultPage();
        //组装查询
        EntityWrapper<CashExpenditure> wrapper = new EntityWrapper<CashExpenditure>();
        if (StringUtils.isNotBlank(cashExpenditure.getPlatform())&&Const.DEFAULT_PH.equals(ShiroKit.getUser().getDeptcode()))
            wrapper.eq("platform",cashExpenditure.getPlatform());
        else
            wrapper.eq("platform",ShiroKit.getUser().getDeptcode());
        //组装查询条件
        if(StringUtils.isNotBlank(beginDate)) {
            wrapper.ge("rev_date", beginDate);
        }else{
            wrapper.ge("rev_date", DateUtil.today(0));
        }
        if(StringUtils.isNotBlank(endDate)) {
            wrapper.le("rev_date", endDate);
        }else{
            wrapper.le("rev_date", DateUtil.today(1));
        }
        if(type!=null){
            wrapper.eq("type", type);
        }
        wrapper.orderBy("rev_date",true);

        Page<CashExpenditure> object =cashExpenditureService.serach(page,wrapper);

        //填充字典类型
        object.setRecords((List<CashExpenditure>)new BaseModelWarpper(object.getRecords(),CashExpenditure.class).warpToObj());
        latelyReord(object,cashExpenditure,beginDate);
        return super.packForBT(object);

    }
    /**
     * 描述:最近一条
     * 创建人: xiang
     * 日期: 2018/8/16
     * 时间: 15:46
     */
    public void latelyReord(Page<CashExpenditure> object,CashExpenditure cashExpenditure,String beginDate){
        //没有记录 默认查出最近一条
            CashExpenditure cashExpenditure1= cashExpenditureService.selectOne( new  EntityWrapper<CashExpenditure>()
                    .eq("platform",cashExpenditure.getPlatform())
                    .lt("rev_date", beginDate)
                    .orderBy("rev_date DESC")
                    .orderBy("id desc")
                    .last("LIMIT 1")
            );
            if(cashExpenditure1!=null){
                CashExpenditure lastCashExpenditure = new CashExpenditure();
                lastCashExpenditure.setNote("上期余额");
                lastCashExpenditure.setBalance(cashExpenditure1.getBalance());
                List<CashExpenditure> list = object.getRecords();
                list.add(0,lastCashExpenditure);
                object.setRecords(list);
            }
    }

    /**
     * 描述:统计PS收入/支出明细分类表
     * 创建人: laoyu
     * 日期: 2018/8/8 0008
     * 时间: 下午 4:37
     */
    @RequestMapping("/total")
    @ResponseBody
    public Object total(CashExpenditure cashExpenditure,@RequestParam(required = false) Integer type, @RequestParam(required = false) String beginDate,@RequestParam(required = false) String  endDate)throws GunsException{

        EntityWrapper<CashExpenditure> wrapper = new EntityWrapper<CashExpenditure>();

            wrapper.eq("platform",ShiroKit.getUser().getDeptcode());
        //组装查询条件
        if(StringUtils.isNotBlank(beginDate)) {
            wrapper.ge("rev_date", beginDate);
        }else{
            wrapper.ge("rev_date", DateUtil.today(0));
        }
        if(StringUtils.isNotBlank(endDate)) {
            wrapper.le("rev_date", endDate);
        }else{
            wrapper.le("rev_date", DateUtil.today(1));
        }
        if(type!=null){
            wrapper.eq("type", type);
        }
        return cashExpenditureService.total(wrapper);

    }

    /**
     * 新增现金收支报表
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    @BussinessLog(value = "新增现金收支报表")
    public Object add(CashExpenditure cashExpenditure) {
        String platform = ShiroKit.getUser().getDeptcode();
        cashExpenditure.setUpdatetime(new Date());
        cashExpenditure.setCreattime(new Date());
        if (cashExpenditure.getRevDate()==null){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"报表统计时间不能为空");
        }
        if (cashExpenditure.getType()==null){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"报表收支类型错误，请重新选择");
        }
        if (cashExpenditure.getDetailsId()==null){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"报表收支明细错误，请重新选择");
        }
        Long order_number = System.currentTimeMillis();
        cashExpenditure.setOrderNumber(order_number.toString());

        boolean isture = cashExpenditureService.insertCash(cashExpenditure);


        Details details = detailsService.selectById(cashExpenditure.getDetailsId());

        //将报表按分类插入不同的细分报表
        //字典Details_type 收支归类  3=应收付应往来
        if (isture&&details.getType().intValue()==Details.Enum_Type.应收付应往来.value.intValue()){
            borrowingInfoService.insertBorrowing(platform,cashExpenditure);

        }

        return SUCCESS_TIP;
    }

    /**
     * 删除现金收支报表
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @BussinessLog(value = "删除现金收支报表")
    public Object delete(@RequestParam Integer cashExpenditureId) {
        CashExpenditure cashExpenditure = cashExpenditureService.selectById(cashExpenditureId);
        if(!cashExpenditure.getPlatform().equals(ShiroKit.getUser().getDeptcode()))
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"对不起您无权删除该条数据");
        cashExpenditureService.deleteById(cashExpenditureId);
        cashExpenditureService.updateBalance(cashExpenditureId,cashExpenditure);
        String order = cashExpenditure.getOrderNumber();
        //如果删除的是借贷则应收应付一起删除
        if (detailsService.selectById(cashExpenditure.getDetailsId()).getType()==CashExpenditure.Enum_DetailType.借贷.value) {
            borrowingInfoService.delete(ShiroKit.getUser().getDeptcode(),order);
        }
        return SUCCESS_TIP;
    }

    /**
     * 修改现金收支报表
     */
    @RequestMapping(value = "/update")
    @BussinessLog(value = "修改现金收支报表")
    @ResponseBody
    public Object update(CashExpenditure cashExpenditure) {

        CashExpenditure oldCashExpenditure = cashExpenditureService.selectById(cashExpenditure.getId());
        if (!oldCashExpenditure.getPlatform().equals(ShiroKit.getUser().getDeptcode()))
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"对不起您无权修改此条数据");
        cashExpenditureService.updateById(cashExpenditure);
        cashExpenditureService.update(oldCashExpenditure,cashExpenditure);
        //如果是应收应付借贷则修改应收应付
        if (detailsService.selectById(cashExpenditure.getDetailsId()).getType() == CashExpenditure.Enum_DetailType.借贷.value){
            borrowingInfoService.update(cashExpenditure,oldCashExpenditure);
        }
        return SUCCESS_TIP;
    }

    /**
     * 现金收支报表详情
     */
    @RequestMapping(value = "/detail/{cashExpenditureId}")
    @ResponseBody
    public Object detail(@PathVariable("cashExpenditureId") Integer cashExpenditureId) {
        return cashExpenditureService.selectById(cashExpenditureId);
    }


    /**
     * 描述:导出ps现金收支表
     * 创建人: laoyu
     * 日期: 2018/8/2 0002
     * 时间: 下午 5:36
     */
    @RequestMapping("/load")
    public void downloadByPoiBaseView(ModelMap modelMap, HttpServletRequest request,
                                      HttpServletResponse response,@RequestParam(required = true)String beginDate,@RequestParam(required = true)String endDate) throws Exception  {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String platform = ShiroKit.getUser().getDeptcode();//获取当前平台
        //组装插叙数据
        EntityWrapper<CashExpenditure> wrapper  = new EntityWrapper<>();
        wrapper.eq("platform",platform);
//        wrapper.like("rev_date",revDate);
        wrapper.ge("rev_date",beginDate);
        wrapper.le("rev_date",endDate);

        //初始化导出的模板表格
        TemplateExportParams params = new TemplateExportParams(
                "exceldoc/cashExpenditure.xlsx");
        Map<String, Object> map = cashExpenditureService.load(cashExpenditureService.selectList(wrapper),platform,beginDate,endDate);

        modelMap.put(TemplateExcelConstants.FILE_NAME, platform+beginDate+"至"+endDate+"收支及成本费用分类明细表（PS）");
        modelMap.put(TemplateExcelConstants.PARAMS, params);
        modelMap.put(TemplateExcelConstants.MAP_DATA, map);
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);

    }



    /**
     * 描述:添加期初余额
     * 创建人: xiang
     * 日期: 2018/8/10
     * 时间: 14:19
     */
    @RequestMapping(value = "/addBalance")
    @ResponseBody
    @BussinessLog(value = "新增现金收支报表")
    public Object addBalance(CashExpenditure cashExpenditure) {
        cashExpenditure.setUpdatetime(new Date());
        cashExpenditure.setCreattime(new Date());
        if (cashExpenditure.getRevDate()==null){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"报表统计时间不能为空");
        }
        if (cashExpenditure.getBalance()==null){
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"请填写正确金额");
        }
        Long order_number = System.currentTimeMillis();
        cashExpenditure.setType(CashExpenditure.Enum_Type.收入.value);
        cashExpenditure.setNote("期初余额");
        cashExpenditure.setOrderNumber(order_number.toString());
        cashExpenditure.setPlatform(ShiroKit.getUser().getDeptcode());
        cashExpenditureService.insert(cashExpenditure);
        return SUCCESS_TIP;
    }


}
